﻿using DigitalScreen.Model;
using LiveCharts.Defaults;
using LiveCharts.Wpf;
using LiveCharts;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows;
using System.Data;

namespace DigitalScreen.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;

        #region 属性

        private string _title;

        public string Title
        {
            get { return _title; }
            set { _title = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Title))); }
        }


        /// <summary>
        /// 大屏幕的标题
        /// </summary>
        //public string Title { get; set; }// 窗口打开的时候设置一次，运行时不做变化 

        // 运行时候   连续的读取实时数据
        // public double Temperature { get; set; }// 将自身变化通知到页面的操作

        private double _teperature;
        /// <summary>
        /// 温度
        /// </summary>
        public double Temperature
        {
            get { return _teperature; }
            set
            {
                _teperature = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Temperature)));
            }
        }
        /// <summary>
        /// 湿度
        /// </summary>
        //public double Humidity { get; set; }
        private double _humidity;

        public double Humidity
        {
            get { return _humidity; }
            set { _humidity = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Humidity))); }
        }


        private string _curTime;

        public string CurTime
        {
            get { return _curTime; }
            set { _curTime = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurTime))); }
        }

        public SeriesCollection StateSeries { get; set; } = new SeriesCollection();

        #endregion



        public ChartValues<ObservableValue> YeildValues1 { get; set; } = new ChartValues<ObservableValue>();
        public ChartValues<ObservableValue> YeildValues2 { get; set; } = new ChartValues<ObservableValue>();
        public ObservableCollection<string> Lables { get; set; } = new ObservableCollection<string>();


        private int _finishRate;
        //完成度
        public int FinishRate
        {
            get { return _finishRate; }
            set
            {
                _finishRate = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FinishRate)));
            }
        }
        //良品率1
        private double _rateValue1;
        public double RateValue1
        {
            get { return _rateValue1; }
            set
            {
                _rateValue1 = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(RateValue1)));
            }
        }
        //良品率2
        private double _rateValue2;
        public double RateValue2
        {
            get { return _rateValue2; }
            set
            {
                _rateValue2 = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(RateValue2)));
            }
        }
        //良品率3
        private double _rateValue3;
        public double RateValue3
        {
            get { return _rateValue3; }
            set
            {
                _rateValue3 = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(RateValue3)));
            }
        }

        //当前产能
        private string _currentUnit = "123456";
        public string CurrentUnit
        {
            get { return _currentUnit; }
            set
            {
                _currentUnit = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentUnit)));
            }
        }
        private string _planUnit = "123456";
        public string PlanUnit
        {
            get { return _planUnit; }
            set
            {
                _planUnit = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(PlanUnit)));
            }
        }

        // VIP INotifyPropertyChanged   ObservableCollection
        // 不存在属性的变化   
        public ObservableCollection<string> Alarms { get; set; } = new ObservableCollection<string>();

        public List<CompareItemModel> WorkerCompareList { get; set; } = new List<CompareItemModel>();

       // public List<BadItemModel> BadScatter { get; set; }
        private List<BadItemModel> _badScatter = new List<BadItemModel>();
        public ObservableCollection<BadItemModel> BadScatter { get; set; } = new ObservableCollection<BadItemModel>();

        string shift;
        string[] shiftA = { "08,09,10,11,12,13,14,15,16,17,18,19" };
        string[] shiftB = { "20,21,22,23,00,01,02,03,04,05,06,07" };
        public MainViewModel()
        {
            InitalSeriesCollection();//初始化饼图 第1列第1行：设备运行状态
            string[] Empolys = new string[] { "赵XX", "钱XX", "孙XX", "李XX", "周XX" };

            string[] BadNames = new string[] { "缺角A", "缺角B", "缺角C", "缺角D", "缺角E", "缺角E", "缺角F", "缺角G" };
            for (int i = 0; i < BadNames.Length; i++)
            {
                BadScatter.Add(new BadItemModel() { Header = BadNames[i], Size = 180 - 20 * i });
            }

            // ADO.NET   
            SqlConnection conn = new SqlConnection("Server=LAPTOP-EERSIA1O;Database=zx_sp_2022;Trusted_Connection=True");
            conn.Open();
            SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("select * from table", conn);
            DataTable dataTable = new DataTable();
            sqlDataAdapter.Fill(dataTable);

            SqlCommand comm = new SqlCommand("insert into table(column) values('test')");
            comm.ExecuteScalarAsync();

            Random random = new Random();
            //后台线程
            Task.Run(async () =>
            {
                while (true)
                {
                    await Task.Delay(1000);
                    Temperature = random.Next(15, 50);
                    Humidity =random.Next(15, 50);
                    CurTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    shift = DateTime.Now.Hour > 7 && DateTime.Now.Hour < 20 ? "白班" : "夜班";

                    this.Title = $"峻凌SMT车间实时状况({shift})";
                    //产能良率区间
                    if (shift == "白班")
                    {
                        Lables.Add("08");
                        Lables.Add("09");
                        Lables.Add("10");
                        Lables.Add("11");
                        Lables.Add("12");
                        Lables.Add("13");
                        Lables.Add("14");
                        Lables.Add("15");
                        Lables.Add("16");
                        Lables.Add("17");
                        Lables.Add("18");
                        Lables.Add("19");
                    }
                    else
                    {
                        Lables.Add("20");
                        Lables.Add("21");
                        Lables.Add("22");
                        Lables.Add("23");
                        Lables.Add("00");
                        Lables.Add("01");
                        Lables.Add("02");
                        Lables.Add("03");
                        Lables.Add("04");
                        Lables.Add("05");
                        Lables.Add("06");
                        Lables.Add("07");
                    }

                    // 这些属性是不需要跨线程操作   WPF底层处理
                    // 保证6位  PadLeft(6-len,' ');random.Next(100, 999_999).ToString("000000")
                    this.CurrentUnit = random.Next(100, 999_999).ToString("000000");
                    this.PlanUnit = random.Next(100, 999_999).ToString("000000");
                    // 设置完成度
                    this.FinishRate = random.Next(10, 100);

                    this.RateValue1 = random.NextDouble();
                    this.RateValue2 = random.NextDouble();
                    this.RateValue3 = random.NextDouble();

                    try
                    {   //需要UI线程处理
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            Alarms.Insert(0, "【H338->厂务冷却水入水温度[℃]】 34->" + DateTime.Now.ToString("mm:ss"));
                            if (Alarms.Count > 6)
                                Alarms.RemoveAt(Alarms.Count - 1);// 滚动   停留
                        });                      
                    }
                    catch (Exception ex)
                    {
                    }

                    foreach (var item in Empolys)
                    {
                        var worker = WorkerCompareList.First(w => w.Header == item);
                        worker.FinishedValue = random.Next(0, (int)worker.PlanValue);// 中途变化    通知到页面
                    }
                    foreach (var item in BadNames)
                    {
                        var bad = BadScatter.First(w => w.Header == item);
                        // 
                        bad.Value = random.NextDouble();  // 
                    }
                    var newList = BadScatter.OrderByDescending(w => w.Value).ToList();
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        BadScatter.Clear();
                        for (int i = 0; i < newList.Count; i++)
                        {
                            newList[i].Size = 180 - 20 * i;
                            BadScatter.Add(newList[i]);
                        }
                    });

                }
            });
            //随机良率数据
            for (int i = 0; i < 12; i++)
            {
                YeildValues1.Add(new ObservableValue(random.Next(20, 380)));
                YeildValues2.Add(new ObservableValue(random.Next(20, 300)));               
            }
            //for (int i = 0; i < shiftA.Length; i++)
            //{
            //    Lables.Add(shiftA[i].ToString());
            //}

            // 添加工人的初始值 
    
            foreach (var item in Empolys)
            {
                WorkerCompareList.Add(new CompareItemModel() { Header = item, PlanValue = random.Next(100, 200), 
                    FinishedValue = 0 });

            }
        }

        private void InitalSeriesCollection()
        {
            //Values = "0.533" Fill = "#FF2BB6FE"
            //StrokeThickness = "0" DataLabels = "True"
            //Title = "普货" LabelPosition = "OutsideSlice"
            PieSeries pieSeries = new PieSeries();
            pieSeries.Title = "普货1";
            pieSeries.LabelPosition = PieLabelPosition.OutsideSlice;
            pieSeries.DataLabels = true;
            pieSeries.StrokeThickness = 0;
            pieSeries.Fill = new SolidColorBrush(Color.FromArgb(255, 43, 182, 254));
            pieSeries.Values = new ChartValues<double>(new List<double> { 0.533 });
            StateSeries.Add(pieSeries);

            pieSeries = new PieSeries();
            pieSeries.Title = "普货2";
            pieSeries.LabelPosition = PieLabelPosition.OutsideSlice;
            pieSeries.DataLabels = true;
            pieSeries.StrokeThickness = 0;
            pieSeries.Fill = Brushes.Red;
            pieSeries.Values = new ChartValues<double>(new List<double> { 0.2 });
            StateSeries.Add(pieSeries);

            pieSeries = new PieSeries();
            pieSeries.Title = "普货3";
            pieSeries.LabelPosition = PieLabelPosition.OutsideSlice;
            pieSeries.DataLabels = true;
            pieSeries.StrokeThickness = 0;
            pieSeries.Fill = new SolidColorBrush(Color.FromArgb(255, 144, 150, 191));
            pieSeries.Values = new ChartValues<double>(new List<double> { 0.167 });
            StateSeries.Add(pieSeries);

            pieSeries = new PieSeries();
            pieSeries.Title = "普货4";
            pieSeries.LabelPosition = PieLabelPosition.OutsideSlice;
            pieSeries.DataLabels = true;
            pieSeries.StrokeThickness = 0;
            pieSeries.Fill = Brushes.DimGray;
            pieSeries.Values = new ChartValues<double>(new List<double> { 0.1 });
            StateSeries.Add(pieSeries);
        }



   



        //   // RateValue1 = 0.3;
        //    //TcpClient tcpClient = new TcpClient();
        //    //tcpClient.Connect("127.0.0.1", 502);
        //    //Modbus.Device.ModbusIpMaster master = Modbus.Device.ModbusIpMaster.CreateIp(tcpClient);
        //    //// 开一个后台线程
        //    //Task.Run(async () =>
        //    //{
        //    //    while (true)
        //    //    {
        //    //        await Task.Delay(1000);
        //    //        // 循环去读取取湿度值    通信
        //    //        ushort[] values = master.ReadHoldingRegisters(1, 0, 2);    // PLC 
        //    //        Temperature = values[0] * 0.1;

        //    //        // 这些属性是不需要跨线程操作   WPF底层处理
        //    //        // 保证6位  PadLeft(6-len,' ');
        //    //        this.CurrentYeild = random.Next(100, 999_999).ToString("000000");
        //    //        // 设置完成度
        //    //        this.FinishRate = random.Next(10, 100);

        //    //        this.RateValue1 = random.NextDouble();

        //    //        try
        //    //        {
        //    //            Application.Current.Dispatcher.Invoke(() =>
        //    //            {
        //    //                Alarms.Insert(0, "【H338->厂务冷却水入水温度[℃]】 34->" + DateTime.Now.ToString("mm:ss"));
        //    //                if (Alarms.Count > 6)
        //    //                    Alarms.RemoveAt(Alarms.Count - 1);// 滚动   停留
        //    //            });
        //    //        }
        //    //        catch (Exception ex)
        //    //        {

        //    //        }

        //    //        YeildValues1[0].Value = random.Next(20, 380);

        //    //        foreach (var item in Empolys)
        //    //        {
        //    //            var worker = WorkerCompareList.First(w => w.Header == item);
        //    //            worker.FinishedValue = random.Next(0, (int)worker.PlanValue);// 中途变化    通知到页面
        //    //        }
        //    //        //
        //    //        foreach (var item in BadNames)
        //    //        {
        //    //            var bad = BadScatter.First(w => w.Header == item);
        //    //            // 
        //    //            bad.Value = random.NextDouble();  // 
        //    //        }
        //    //        var newList = BadScatter.OrderByDescending(w => w.Value).ToList();
        //    //        Application.Current.Dispatcher.Invoke(() =>
        //    //        {
        //    //            BadScatter.Clear();
        //    //            for (int i = 0; i < newList.Count; i++)
        //    //            {
        //    //                newList[i].Size = 180 - 20 * i;
        //    //                BadScatter.Add(newList[i]);
        //    //            }
        //    //        });
        //    //    }
        //    //});
        //    //this.Humidity = 60.5;




        //    //// DataTable  数据表   控件    DataGrid    DataGridView
        //    ////SqlDataAdapter.Fill(DataSet  DataTable)
        //    //for (int i = 0; i < 12; i++)
        //    //{
        //    //    YeildValues1.Add(new ObservableValue(random.Next(20, 380)));
        //    //    YeildValues2.Add(new ObservableValue(random.Next(20, 300)));
        //    //}

        //}

    }
}
